package com.xique.common.core.utils;

import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.xique.common.core.web.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class SmsUtils {

    @Value("${alioss.accessKeyId}")
    private  String accessKeyId;

    @Value("${alioss.accessKeySecret}")
    private  String accessKeySecret;


    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */

    public static  com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }


    /**
     * @description: 发送验证码，存缓存在方法调用处处理
     * @author caogq
     * @date 2021/12/2 14:27
     * @version 1.0
     */

    public  AjaxResult sendVerificationCodeSms(String telephone) throws Exception {

        com.aliyun.dysmsapi20170525.Client client = SmsUtils.createClient(accessKeyId, accessKeySecret);
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(telephone);
        sendSmsRequest.setSignName("喜鹊云社区");
        //通用验证码模板
        sendSmsRequest.setTemplateCode("SMS_229096993");
        String randomCode = MathUtil.getRandom(6);
        sendSmsRequest.setTemplateParam("{\"code\":\"" + randomCode+ "\"}");
        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
        if (sendSmsResponse.getBody().getCode() != null && sendSmsResponse.getBody().getCode().equals("OK")) {
            AjaxResult ajaxResult = AjaxResult.success("短信发送成功！");
            ajaxResult.put("randomCode",randomCode);
            return ajaxResult;
        } else {
            return AjaxResult.error("短信发送失败！，请联系管理员！");
        }
    }

}
